﻿using System;
using System.Drawing;
using System.Windows.Forms;
using holysheng.RegeditX;

namespace RegistryGUI
{
    public partial class MainForm : System.Windows.Forms.Form
    {
        #region 初使化
        RegComputer _regComputer = new RegComputer();
        RegXML _regXML = new RegXML();
        int treenode_setting_index; // TreeNode的当前选中索引
        AddForm addForm = new AddForm();
        EditForm editForm = new EditForm();
        EditForms editForms = new EditForms();

        public MainForm()
        {
            InitializeComponent();
            AddDataGridViewHeader(dataGridView_user, dataGridView_system);//添加表头
            AddDataGridViewHeader(dataGridView_setting_user, dataGridView_setting_system);//添加表头
        }

        // 定义表头，也可以在设计器里直接定义，但必须将DataPropertyName指定为 RegVar 或 RegValue
        private void AddDataGridViewHeader(DataGridView user, DataGridView system)
        {
            System.Windows.Forms.DataGridViewTextBoxColumn userHeaderRegVar = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "RegVar",
                HeaderText = "变量",
                Width = 150
            };

            System.Windows.Forms.DataGridViewTextBoxColumn userHeaderRegValue = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "RegValue",
                HeaderText = "值",
                AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            };

            System.Windows.Forms.DataGridViewTextBoxColumn userHeaderStatus = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "Status",
                HeaderText = "状态",
                Visible = false//让状态不可见
            };

            user.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { userHeaderRegVar, userHeaderRegValue, userHeaderStatus });


            System.Windows.Forms.DataGridViewTextBoxColumn systemHeaderRegVar = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "RegVar",
                HeaderText = "变量",
                Width = 150
            };

            System.Windows.Forms.DataGridViewTextBoxColumn systemHeaderRegValue = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "RegValue",
                HeaderText = "值",
                AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            };

            System.Windows.Forms.DataGridViewTextBoxColumn systemHeaderStatus = new System.Windows.Forms.DataGridViewTextBoxColumn
            {
                DataPropertyName = "Status",
                HeaderText = "状态",
                Visible = false//让状态不可见
            };

            system.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { systemHeaderRegVar, systemHeaderRegValue, systemHeaderStatus });
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox_user.Text = Environment.UserName + "的环境变量";
            LoadAllForm();
        }

        //加载所有窗口
        private void LoadAllForm()
        {
            _regComputer.BindingDataSource(dataGridView_user, dataGridView_system);//绑定计算机环境变量
            _regXML.BindingDataSource(treeViewOfSetting, dataGridView_setting_user, dataGridView_setting_system);//绑定Xml设置

            treeViewOfSetting.ExpandAll();//展开TreeView控件中的所有项
        }
        #endregion

        #region 公共方法

        // 导入导出环境变量
        public bool ImportAndExport(DataGridView datagridview, RegBindingList list)
        {
            int count = datagridview.SelectedRows.Count;
            if (count < 0) return false;
            DataGridViewRow row;
            string strYes = "导入导出成功：";
            string strNo = "   导入导出失败，存在重复变量名：";
            for (int i = count - 1; i >= 0; i--) // 遍历不能用foreach，因为会倒序
            {
                row = datagridview.SelectedRows[i];
                string regVar = row.Cells[0].Value.ToString();
                string regValue = row.Cells[1].Value.ToString();
                Reg reg = new Reg { RegVar = regVar, RegValue = regValue }; // 添加元素

                if (list.AddReg(reg, BaseReg.RegStatus.AddReg)) // 添加
                { strYes += regVar + "；"; }
                else { strNo += regVar + "；"; }
            }
            string str = "";
            if (strYes != "导入导出：")
            { str += strYes; }
            if (strNo != "   导入导出失败，存在重复变量名：")
            { str += strNo; }
            toolStripStatusLabel1.Text = str;
            return true;
        }

        // 删除环境变量
        private bool Del_dataGridView(DataGridView datagridview, RegBindingList list)
        {
            string str = "删除成功：";
            string name;
            if (datagridview.SelectedRows.Count == 0) return false;
            foreach (DataGridViewRow row in datagridview.SelectedRows) // todo 系统的path变量，应不允许删除
            {
                name = row.Cells[0].Value.ToString();
                list.DelReg(name); // 删除变量名
                str += name + "；";
            }
            datagridview.Refresh();
            toolStripStatusLabel1.Text = str;
            return true;
        }

        // 新增环境变量
        private bool Add_dataGridView(DataGridView datagridview, RegBindingList list)
        {
            addForm.SetText("", "");
            addForm.SetSelectVar();
            if (addForm.ShowDialog(this) == DialogResult.OK)
            {
                string newRegVar = addForm.Var;
                string newRegValue = addForm.Value;
                if (newRegVar != null || newRegVar != "")
                {
                    if (list.AddReg(newRegVar, newRegValue, BaseReg.RegStatus.AddReg))
                    {
                        toolStripStatusLabel1.Text = "新增成功：" + newRegVar;
                        datagridview.FirstDisplayedScrollingRowIndex = datagridview.Rows.Count - 1; // 跳转最后一行
                    }
                    else
                    {
                        toolStripStatusLabel1.Text = "新增失败，存在重复变量名：" + newRegVar;
                    }
                }
            }
            return false;
        }


        // 编缉环境变量，点击事件
        private bool Edit_dataGridView(DataGridView datagridview, RegBindingList list)
        {
            if (datagridview.SelectedRows.Count != 1) return false;//只编缉当前选中的一个，如多个选中，则不能编缉
            int rowIndex = datagridview.SelectedRows[0].Index;
            return Edit_dataGridView(rowIndex, datagridview, list);
        }

        // 最终调用的编缉环境变量方法
        private bool Edit_dataGridView(int rowIndex, DataGridView datagridview, RegBindingList list)
        {
            //判断双击的是否为标题
            if (rowIndex >= 0)
            {
                string oldRegVar = datagridview.Rows[rowIndex].Cells[0].Value.ToString();
                string oldRegValue = datagridview.Rows[rowIndex].Cells[1].Value.ToString();
                string isPath = String.Copy(oldRegVar);
                if (isPath.ToLower() == "path") // 如果是path环境变量
                {
                    string[] strs = oldRegValue.Split(';'); // 转换为以;分割的字符串数组
                    editForms.SetDataGridViewColumns(oldRegVar, strs);
                    if (editForms.ShowDialog(this) == DialogResult.OK)
                    {
                        list.EditReg("path", datagridview.Rows[rowIndex].Cells[1].Value.ToString(), "path", editForms.value);
                    }
                }
                else // 如果是正常的环境变量
                {
                    editForm.SetText(oldRegVar, oldRegValue);
                    editForm.SetSelectTextBox();

                    // 编缉时考虑是否重复
                    if (editForm.ShowDialog(this) == DialogResult.OK)
                    {
                        string newRegVar = editForm.var;
                        string newRegValue = editForm.value;
                        if (list.EditReg(datagridview.Rows[rowIndex].Cells[0].Value.ToString(), datagridview.Rows[rowIndex].Cells[1].Value.ToString(), newRegVar, newRegValue))
                        {
                            toolStripStatusLabel1.Text = "编缉成功：" + newRegVar;
                            datagridview.Refresh();
                            return true;
                        }
                        toolStripStatusLabel1.Text = "编缉失败，存在重复变量名：" + newRegValue;
                    }
                }
                datagridview.Refresh();
            }
            return false;
        }

        #endregion 公共方法

        #region 事件：导入导出
        private void Button_user_export_Click(object sender, EventArgs e)
        {
            ImportAndExport(dataGridView_user, _regXML.NameList[treenode_setting_index].User);
        }

        private void Button_system_export_Click(object sender, EventArgs e)
        {
            ImportAndExport(dataGridView_system, _regXML.NameList[treenode_setting_index].System);
        }

        private void Button_setting_user_import_Click(object sender, EventArgs e)
        {
            ImportAndExport(dataGridView_setting_user, _regComputer.User);
        }

        private void Button_setting_system_import_Click(object sender, EventArgs e)
        {
            ImportAndExport(dataGridView_setting_system, _regComputer.System);
        }
        #endregion

        #region 事件：删除环境变量
        private void Button_user_remove_Click(object sender, EventArgs e)
        {
            Del_dataGridView(dataGridView_user, _regComputer.User);
        }

        private void Button_system_remove_Click(object sender, EventArgs e)
        {
            Del_dataGridView(dataGridView_system, _regComputer.System);
        }

        private void Button_setting_user_delete_Click(object sender, EventArgs e)
        {
            Del_dataGridView(dataGridView_setting_user, _regXML.NameList[treenode_setting_index].User);
        }

        private void Button_setting_system_delete_Click(object sender, EventArgs e)
        {
            Del_dataGridView(dataGridView_setting_system, _regXML.NameList[treenode_setting_index].System);
        }
        #endregion

        #region 事件：新增环境变量
        private void Button_user_add_Click(object sender, EventArgs e)
        {
            Add_dataGridView(dataGridView_user, _regComputer.User);
        }

        private void Button_system_add_Click(object sender, EventArgs e)
        {
            Add_dataGridView(dataGridView_system, _regComputer.System);
        }

        private void Button_setting_user_add_Click(object sender, EventArgs e)
        {
            Add_dataGridView(dataGridView_setting_user, _regXML.NameList[treenode_setting_index].User);
        }
        private void Button_setting_system_add_Click(object sender, EventArgs e)
        {
            Add_dataGridView(dataGridView_setting_system, _regXML.NameList[treenode_setting_index].System);
        }
        #endregion

        #region 事件：节点
        // 点击事件：用于更换显示的配置名
        private void TreeViewOfSetting_AfterSelect(object sender, TreeViewEventArgs e)
        {
            treenode_setting_index = (int)treeViewOfSetting.SelectedNode.Index;

            // 根据索引重新绑定TreeNode
            _regXML.BindingDataSource(dataGridView_setting_user, dataGridView_setting_system, treenode_setting_index);
        }

        private void ButtonAddTreeNode_Click(object sender, EventArgs e)
        {
            try
            {
                _regXML.AddName();
                _regXML.BindingDataSource(treeViewOfSetting);
                treeViewOfSetting.SelectedNode = treeViewOfSetting.Nodes[treeViewOfSetting.Nodes.Count - 1]; // 设置新增的节点为选中项
                toolStripStatusLabel1.Text = "添加新设置成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show("新增节点错误，错误代码为：" + ex.ToString());
            }
        }

        // 删除事件：如选中的节点下无详细配置，直接删除，否则提示（防止误删）
        // 如果节点是最后一个，则置DataGridView的DataSouse为null
        private void ButtonDelTreeNode_Click(object sender, EventArgs e)
        {
            try
            {
                if (treeViewOfSetting.Nodes.Count == 1)
                {
                    MessageBox.Show("最后一个结点，不允许删除");
                    return;
                }
                if (dataGridView_setting_user.Rows.Count > 0 || dataGridView_setting_system.Rows.Count > 0)
                {
                    if (MessageBox.Show("当前设置名下存在数据，确定删除？？？", "提示信息", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Cancel) return;
                }
                toolStripStatusLabel1.Text = "删除成功：" + treeViewOfSetting.SelectedNode.Text;
                _regXML.NameList.RemoveAt(treenode_setting_index);
                treeViewOfSetting.SelectedNode.Remove();
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除节点失败，错误代码为：" + ex.ToString());
            }
        }

        // 双击节点，开始编缉
        private void TreeViewOfSetting_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode node = treeViewOfSetting.GetNodeAt(clickPoint);
                if (node != null)//判断点击的是否是一个节点
                {
                    treeViewOfSetting.SelectedNode = node;//选中节点
                    treeViewOfSetting.LabelEdit = true;
                    treeViewOfSetting.SelectedNode.BeginEdit();
                }
            }
        }

        // 节点编缉事件结束
        private void TreeViewOfSetting_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            string newName = e.Label;
            _regXML.NameList[treenode_setting_index].Name = newName;
        }
        #endregion

        #region 事件：编缉环境变量
        private void Button_user_edit_Click(object sender, EventArgs e)
        {
            Edit_dataGridView(dataGridView_user, _regComputer.User);
        }

        private void Button_system_edit_Click(object sender, EventArgs e)
        {
            Edit_dataGridView(dataGridView_system, _regComputer.System);
        }

        private void Button_setting_user_edit_Click(object sender, EventArgs e)
        {
            Edit_dataGridView(dataGridView_setting_user, _regXML.NameList[treenode_setting_index].User);
        }

        private void Button_setting_system_edit_Click(object sender, EventArgs e)
        {
            Edit_dataGridView(dataGridView_setting_system, _regXML.NameList[treenode_setting_index].System);
        }
        private void dataGridView_user_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Edit_dataGridView(e.RowIndex, dataGridView_user, _regComputer.User);
        }

        private void dataGridView_system_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Edit_dataGridView(e.RowIndex, dataGridView_system, _regComputer.System);
        }

        private void dataGridView_setting_user_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Edit_dataGridView(e.RowIndex, dataGridView_setting_user, _regXML.NameList[treenode_setting_index].User);
        }

        private void dataGridView_setting_system_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            Edit_dataGridView(e.RowIndex, dataGridView_setting_system, _regXML.NameList[treenode_setting_index].System);
        }
        #endregion

        #region 事件：保存
        private void Button_user_save_Click(object sender, EventArgs e)
        {
            if (_regComputer.SaveUserReg())
                MessageBox.Show("保存成功");
        }

        private void Button_system_save_Click(object sender, EventArgs e)
        {
            if (_regComputer.SaveSystemReg())
                MessageBox.Show("保存成功");
        }

        //保存到XML
        private void ButtonSaveTreeNode_Click(object sender, EventArgs e)
        {
            if (_regXML.SaveReg())
                MessageBox.Show("保存成功");
        }
        #endregion


    }
}
